package com.fare.taluo.core.domain.crawl.adapter.sub;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;

import com.fare.taluo.core.domain.config.city.PortEntity;
import com.fare.taluo.core.domain.config.line.FeiChangZhunFlightInfoEntity;
import com.fare.taluo.core.domain.crawl.CrawlCSAirLineModel;
import com.fare.taluo.core.domain.crawl.adapter.AbstractAdapter;
import com.fare.taluo.util.HTMLParseUtil;

public class FeiChangZhunAdapter extends AbstractAdapter {
	private HttpClient client = null;
	private static final String CONNECT_URL = "http://www.veryzhun.com/search.asp";
	public FeiChangZhunAdapter(CrawlCSAirLineModel portModel) {
		super(portModel);
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		List<Object> result = new ArrayList<Object>();
		Map<String,Element>  elementMap = (Map<String,Element>)  fetchObject;
        Collection<Element> c = elementMap.values();
        Iterator it = c.iterator();
        //对于每个table表格
        for (; it.hasNext();) {
        	Element tableElement = (Element) it.next();
        	Source source = new Source(tableElement.toString());
        	//获得所有行
        	List<Element> trLists = source.getAllElements("tr");
        	for (Element trElement : trLists) {
        		FeiChangZhunFlightInfoEntity feiEntity = getTrInfo(trElement);
        		result.add(feiEntity);
			}
        }
		return result;
	}
	private FeiChangZhunFlightInfoEntity getTrInfo(Element trElement){
		try {
			List<Element> tdLists = trElement.getAllElements("td");
				// 航班号
				Element td0 = tdLists.get(0);
				String flightNo = td0.getAllElements("span").get(0).getAllElements("a").get(1).getTextExtractor().toString();
				
				//起飞时间
				Element td1 = tdLists.get(1);
				String startTime = td1.getAllElements("span").get(0).getTextExtractor().toString();
				
				Element td5 = tdLists.get(5);
				String endTime = td5.getAllElements("span").get(0).getTextExtractor().toString();
				
				FeiChangZhunFlightInfoEntity feiEntity = new FeiChangZhunFlightInfoEntity();
				feiEntity.setCompanyCode(flightNo.substring(0, 2));
				feiEntity.setEntryTime(new Date());
				feiEntity.setFlightEndTime(endTime);
				feiEntity.setFlightStartTime(startTime);
				feiEntity.setFlightNo(flightNo);
				feiEntity.setFromCity(portModel.getFromCityCode());
				feiEntity.setToCity(portModel.getToCityCode());
				feiEntity.setFromCityName(portModel.getFromCity());
				feiEntity.setToCityName(portModel.getToCity());
				return feiEntity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	@Override
	public String getUrl() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object fetch(String url) throws Exception {
		client = new DefaultHttpClient();
		//获得返回的第一页
		String firstPage = getPageString(1); 
		Map<String,Element> map = new HashMap<String, Element>();
		
		//若该航线没有信息则返回null
		if(firstPage.indexOf("未查到您所需要的航班信息")!=-1){
			return null;
		}
		
		//先保存第一页数据
		Element firstTable = new Source(firstPage).getFirstElementByClass("hbdtinfo1");
		map.put("1", firstTable);
		//若数据只有一页直接返回
		if(firstPage.indexOf("下一页")==-1){
			return map;
		}
		//假设最大分页数为100
		for (int i = 2; i < 100; i++) {
			String  pageStr = getPageString(i);
			
			Element element = new Source(pageStr).getFirstElementByClass("hbdtinfo1");
		//	System.out.println(element.toString());
			map.put(""+i, element);
			//若没有下一页
			if(pageStr.indexOf("下一页")==-1){
				break;
			}
		}
		return map;
	}
	
	
	/**
	 * 获得第一页
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 * @throws URISyntaxException 
	 */
	private String getPageString(int page) throws IllegalStateException, IOException, URISyntaxException{
		String url = "http://www.veryzhun.com/search.asp?dep="+URLEncoder.encode(portModel
				.getFromCity(), "gb2312")+"&arr="+URLEncoder.encode(portModel
						.getToCity(), "gb2312");
		if(page > 1){
			url += "&page=" + page ;
		}
		HttpGet request = new HttpGet();  
        request.setURI(new URI(url)); 
        HttpResponse response = client.execute(request);
		InputStream is = response.getEntity().getContent();
		BufferedInputStream bis = new BufferedInputStream(is);
		ByteArrayBuffer baf = new ByteArrayBuffer(20);

		int current = 0;
		while ((current = bis.read()) != -1) {
			baf.append((byte) current);
		}
		String pageString = new String(baf.toByteArray(), "gb2312"); // 指定编码
		return pageString;
	}
	
	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

}
